#!/usr/bin/env node
//用流的方式编写任务二
const http=require('http'),
      fs=require('fs'),
      log=console.log;

http.createServer((req,res)=>{
//实质
//const server=http.createServer();
//server.listen(8080);
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log(req.headers);
  log('');

  const file=__dirname+req.url;
  
  //错误处理方式一：主动防御
  /*
  if(fs.existsSync(file)) {
    fs.createReadStream(file).pipe(res);      
  } else {
    res.statusCode = 404;
    res.end(req.url + ' not exist!');          
  }
  */

  //错误处理方拾二：error事件捕获
    let s = fs.createReadStream(file);
    s.on('error', (err) => {
      console.log(err.message);
      res.statusCode = 404;
      res.end(err.message);                   
    });
   s.pipe(res);
  
}).listen(8080);







